package userhandler

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/devrule"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/userprofitlog"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
)

// ------- 用户相关API请求处理 userHandler -------

// 获取所有用户列表
func GetAllUserList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.Bind(&param)).Unwrap()
	//param.UserLoginIsAdmin = IsAdmin  // 当前登录用户角色 1管理员 2运营商 3合作伙伴(代理商、商户) 4 员工
	//param.ParentId = userId           // 当前登录用户ID

	param.UserId = userId

	// 获取当前用户的的下级用户列表
	data := dao.NewUserDao().GetUserListByArrParentId(param)
	lists := data.Unwrap().([]*users.UserInfoWithAgent)

	//lists := dao.NewUserDao().GetUserListByArrParentId(param).Unwrap().([]*users.UserInfoWithAgent)
	for _, lst := range lists {
		logic.NewUserLogic().FindUserChildrenList(lst.ID, lst)
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 获取登录帐号对应的员工列表
func GetUserListMaintainer(ctx *gin.Context) {
	param := &struct {
		Id           int `form:"id"`
		IsAdmin      int `form:"isAdmin"`      // 登录的角色
		MaintainerId int `form:"maintainerId"` // 维护者ID
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	var staffList []*users.UserModel
	if param.MaintainerId > 0 && param.IsAdmin == 2 { // 运营商修改商户
		// 获取维护者信息
		userInfo := dao.NewUserDao().GetUserInfoById(param.MaintainerId).Unwrap().(*users.UserModel)
		staffList = dao.NewUserDao().GetMaintainerListByParentId(userInfo.ParentID).Unwrap().([]*users.UserModel)
	} else {
		if param.IsAdmin == 2 || param.IsAdmin == 3 { // 运营商、代理商
			staffList = dao.NewUserDao().GetMaintainerListByParentId(param.Id).Unwrap().([]*users.UserModel)
		} else {
			staffList = dao.NewUserDao().GetMaintainerListById(param.Id).Unwrap().([]*users.UserModel)
		}
	}

	Response(ctx)("", CodeSuccess, staffList)(OK)
}

// 获取供应商列表
func GetUserListMsc(ctx *gin.Context) {

	mscList := dao.NewUserDao().GetMscListByIsAdmin().Unwrap().([]*users.UserModel)
	Response(ctx)("", CodeSuccess, mscList)(OK)
}

// HandleGetUserList 查询 - 有分页、有查询参数
func HandleGetUserList(ctx *gin.Context) {
	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := dao.NewUserDao().GetUserList(param)
	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

func GetUserListByName(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		Name string `form:"name"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 分页信息
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserListByName(param.Name).Unwrap(),
	)(OK)
}

func HandleGetUserByPhone(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		Phone  string `form:"phone"`
		UserId int    `form:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 分页信息
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().CheckUserInfoByPhone(param.Phone, param.UserId).Unwrap(),
	)(OK)
}

// 检测手机号是否已被注册
func HandleCheckUserProfitProportion(ctx *gin.Context) {
	parentId, err := helper.GetParentIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}

	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserInfoByParentId(parentId).Unwrap(),
	)(OK)
}

func HandleGetUserInfoByPid(ctx *gin.Context) {
	param := &struct {
		ParentId int `form:"parentId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	log.Println(param)
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserInfoById(param.ParentId).Unwrap(),
	)(OK)
}

func HandleGetUserInfoByPidAllList(ctx *gin.Context) {
	param := &struct {
		ParentId int `form:"parentId"`
		KaUserId int `form:"kaUserId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().QueryParentList(param.ParentId, param.KaUserId).Unwrap(),
	)(OK)
}

// GetAllChildUserListByUserName 根据用户名查找当前登录用户下的子用户
func GetAllChildUserListByUserName(ctx *gin.Context) {
	param := &struct {
		UserName string `form:"userName"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		userId = 2
	}
	Response(ctx)("", CodeSuccess, dao.NewUserDao().GetUserListByUserName(param.UserName, userId).Unwrap())(OK)
}

// 获取当前用户下的所有用户，不能查询所有用户
func HandleGetAllAgentUserList(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		UserName string `form:"userName"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	//fmt.Println("HandleGetAllAgentUserList :", param.UserName)

	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		userId = 2
	}

	// 分页信息
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetAllAgentUserNoLoginUserList(param.UserName, userId).Unwrap(),
	)(OK)
}

// 获取上级代理商列表
func HandleGetSuperiorAgentList(ctx *gin.Context) {
	param := &struct {
		Id           int `form:"id"`
		IsAdmin      int `form:"isAdmin"`      // 登录的角色
		MaintainerId int `form:"maintainerId"` // 维护者ID
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	var agentList []*users.UserInfoWithAgent
	//if param.MaintainerId > 0 && param.IsAdmin == 2 { // 运营商修改商户
	//	// 获取维护者信息
	//	userInfo := dao.NewUserDao().GetUserInfoById(param.MaintainerId).Unwrap().(*users.UserModel)
	//	agentList = dao.NewUserDao().GetSupAgentUserListByParentId(userInfo.ParentID, 0).Unwrap().([]*users.UserInfoWithAgent)
	//} else {
	if param.IsAdmin == 2 { // 运营商
		agentList = dao.NewUserDao().GetSupAgentUserListByParentId(param.Id, 2).Unwrap().([]*users.UserInfoWithAgent)
	} else if param.IsAdmin == 3 { // 代理商
		agentList = dao.NewUserDao().GetSupAgentUserListByParentId(param.Id, 0).Unwrap().([]*users.UserInfoWithAgent)
	} else { // 员工 (不考虑管理员)

		userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)

		isPlace := 0
		if userInfo.ParentID == 2 {
			isPlace = 2 //只有运营商员工才能添加商户代理
		}

		log.Println("33333 :", isPlace, userInfo.ParentID)
		agentList = dao.NewUserDao().GetSupAgentUserListByParentId(userInfo.ParentID, isPlace).Unwrap().([]*users.UserInfoWithAgent)
	}
	//}

	Response(ctx)("", CodeSuccess, agentList)(OK)
}

// 获取上级代理商列表
func HandleGetUserAgent(ctx *gin.Context) {
	param := &struct {
		Id int `form:"id"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	var agentList []*users.UserInfoWithAgent
	agentList = dao.NewUserDao().GetSupAgentUserListByParentId(param.Id, 0).Unwrap().([]*users.UserInfoWithAgent)

	Response(ctx)("", CodeSuccess, agentList)(OK)
}

func HandleGetAgentPlaceUserList(ctx *gin.Context) {
	//userId, err := helper.GetUserIdFromCtx(ctx)
	//if err != nil {
	//	dingo.ErrorIf(err).Unwrap()
	//}
	parentId, err := helper.GetParentIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.ParentId = parentId
	param.IsAdmin = 3
	param.IsPlace = 2

	resultList := make([]users.UserInfoWithAgent, 0)

	data := dao.NewUserDao().GetAgentUserList(param)
	lists := data.Unwrap().([]users.UserInfoWithAgent)
	for _, lst := range lists {
		// 获取该用户下的所有代理商的用户ID
		pidArr := []int{lst.ID}
		userIdArr := make([]int, 0)
		isRecursive := true
		// 递归 无限查询下级
		for isRecursive {
			tempUserIdArr := dao.NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)

			if len(tempUserIdArr) == 0 {
				isRecursive = false
			} else {
				userIdArr = append(userIdArr, tempUserIdArr...)
				pidArr = tempUserIdArr
				//log.Println("当前pid数组：",pidArr)
				//log.Println("当前userIdArr数组：",userIdArr)
			}
		}
		//placeTotalModel := dao.NewPlaceDao().TotalPlaceByUserId(userIdArr).Unwrap().(*placeresp.TotalPlaceDevices)
		//lst.DeviceCount = placeTotalModel.DeviceCount
		//lst.PlaceCount = placeTotalModel.PlaceCount

		// 加入新的List中
		resultList = append(resultList, lst)
		//fmt.Println("lst.DeviceCount: ", lst.DeviceCount)
	}
	//userInfo := dao.NewUserDao().GetAgentUserListById(userId).Unwrap().(*users.UserInfoWithAgent)
	//logic.NewUserLogic().FindAgentChildrenList(userId, userInfo)
	//lists = append(lists, userInfo)

	//fmt.Println("hahahah: ", len(lists), "   :", lists)
	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       resultList,
	})(OK)
}

func GetPlaceListNoPager(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		PlaceName string `form:"placeName"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前代理商ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, err := helper.GetIsAdminFromCtx(ctx) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 分页信息
	Response(ctx)("",
		CodeSuccess,
		dao.NewPlaceDao().GetPlaceListNoPager(param.PlaceName, loginUserId, isAdmin).Unwrap())(OK)
}

// 获取商户用户列表
func GetPlaceUserListByName(ctx *gin.Context) {
	//param := &request.UserList{}
	//dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	//param.IsAdmin = 3
	//param.IsPlace = 1
	//param.PageSize = 0
	//param.PageNo = 0
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	param.UserLoginIsAdmin = IsAdmin
	param.UserLoginIsPlace = IsPlace
	param.ParentId = userId // 当前登录用户ID
	//param.IsAdmin = helper.TypeNumIsAdminAgent // 代理商
	//param.IsPlace = 1
	if param.Name == "" {
		param.PageSize = 10
		param.PageNo = 1
	}

	Response(ctx)("", CodeSuccess,
		dao.NewUserDao().GetPlaceUserList(param).Unwrap(),
	)(OK)
}

// GetUserAllListByName 获取商户/代理商/分公司用户列表
func GetUserAllListByName(ctx *gin.Context) {
	param := &struct {
		Name string `form:"name"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	//fmt.Println("HandleGetAllAgentUserList :", param.UserName)

	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		userId = 2
	}

	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserAllListByName(param.Name, userId, IsAdmin).Unwrap(),
	)(OK)
}

// 获取商户价格信息
//func HandleGetPlacePrice(ctx *gin.Context) {
//	param := &struct {
//		PlaceId      int `form:"id"`
//		DeviceTypeId int `form:"deviceTypeId"`
//	}{}
//	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
//
//	Response(ctx)("", CodeSuccess,
//		dao.NewPricesDao().GetPlacePrice(param.PlaceId, param.DeviceTypeId).Unwrap())(OK)
//}

//获取省市县
func HandleGetRegions(ctx *gin.Context) {
	param := &struct {
		RegionsId int `form:"regionsId"`
		Level     int `form:"level"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsByLevel(param.Level).Unwrap())(OK)
}

//获取省市县
func HandleGetRegionsByParent(ctx *gin.Context) {
	param := &struct {
		Parent int `form:"parent"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsListByParent(param.Parent).Unwrap())(OK)
}

func HandleGetStaffUserList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.IsAdmin = 4
	param.ParentId = userId

	// 查询结果
	data := dao.NewUserDao().GetStaffUserList(param)
	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

// GetUser 查询 - 详情
func GetUser(ctx *gin.Context) {

}

// HandleInsertUser 新增
func HandleInsertUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ParentId = userId
	Response(ctx)("", CodeInsertSuccess, dao.NewUserDao().InsertUser(param).Unwrap())(OK)
}

func HandleInsertPlace(ctx *gin.Context) {
	param := &request.PlaceInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	//fmt.Println("现在的PID: ", param.PlaceName,param.UserId,param.Name,param.ParentId)
	placeInfo := dao.NewUserDao().InsertPlaceInfo(param).Unwrap().(*placemodel.PlaceModel)
	// 添加计费规则
	// 获取所有计费规则
	ruleInfos := dao.NewPricesDao().GetDeviceRuleInfoList().Unwrap().([]devrule.DeviceRulesModel)
	// 新增商户计费规则
	for _, ruleInfo := range ruleInfos {
		m := prices.New()
		m.DeviceTypeId = ruleInfo.TypeId
		m.PlaceId = placeInfo.Id
		m.Status = ruleInfo.Status
		m.ProductId = utils.Str2Md5(helper.GenerateUUID())

		// -----套餐模式 开始------
		m.UseDuration = ruleInfo.UseDuration // 使用时长
		m.PayMoney = ruleInfo.PayMoney       // 支付金额-单位分
		m.SetMealNum = ruleInfo.SetMealNum   // 规则序号
		m.RuleName = ruleInfo.RuleName       // 规则名
		m.IsRecommend = ruleInfo.IsRecommend // 是否推荐
		m.Priority = ruleInfo.Priority       // 排序
		// -----套餐模式 结束------

		// -----计时模式 开始------
		m.MaxPayPrice = ruleInfo.MaxPayPrice           // 日封顶价格
		m.PayIntervalPrice = ruleInfo.PayIntervalPrice // 每60分钟支付2元
		m.PayInterval = int(ruleInfo.PayInterval)      // 每60分钟支付2元
		m.MaxTime = ruleInfo.MaxTime                   // 最大使用时长
		m.BasePrice = ruleInfo.BasePrice               // 最低使用价格
		m.BaseTimes = int(ruleInfo.BaseTimes)          // 最低使用时长
		m.FreeTimes = int(ruleInfo.FreeTimes)          // 免费使用时长
		m.Deposit = ruleInfo.Deposit                   //  押金
		// -----计时模式 结束------

		m.CreateAt = dingo.Time(time.Now().Unix())
		dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
	}

	Response(ctx)("新增成功", CodeSuccess, placeInfo)(OK)
}

// HandleUpdateUser 修改
func HandleUpdateUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ParentId = userId
	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUser(param).Unwrap())(OK)
}

// 修改用户状态
func HandleUpdateUserStatus(ctx *gin.Context) {
	param := &struct {
		Id     int  `json:"id" binding:"required,gt=0"`
		Status int8 `json:"status" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUserStatus(param.Id, param.Status).Unwrap())(OK)
}

// 修改用户密码
func HandleUpdateUserPassword(ctx *gin.Context) {

	userId, err := helper.GetUserIdFromCtx(ctx)   // 获取当前登录用户ID
	userName, _ := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		Id        int    `json:"id" binding:"required,gt=0"`
		Passoword string `json:"password" binding:"required,min=6"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	// 重置密码
	password := utils.EncryptPassword(param.Passoword)
	isReset := dao.NewUserDao().UpdateUserPassword(param.Id, password).Unwrap().(bool)
	if isReset {
		upl := userprofitlog.UserProfitLog{}
		upl.ParentId = userInfo.ParentID
		upl.UserId = userInfo.ID
		upl.UserName = userInfo.UserName
		upl.OperationUserId = userId
		upl.OperationUserName = userName
		upl.OperateIP = ctx.ClientIP()
		upl.Change = int8(userInfo.ProfitProportion)
		upl.IsPlace = int8(userInfo.IsPlace)
		upl.ProfitProportion = int8(userInfo.ProfitProportion)
		upl.Description = "重置密码成功"
		p := &request.AdminUserInsertReq{}
		dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, p, userInfo) // 添加订单操作日志
		Response(ctx)("重置密码成功", CodeSuccess, true)(OK)
		return
	} else {
		Response(ctx)("重置密码失败", CodeError, false)(OK)
		return
	}

}

// 修改员工用户密码
func HandleUpdateUserStaffPassword(ctx *gin.Context) {

	param := &struct {
		Id        int    `json:"id" binding:"required,gt=0"`
		Passoword string `json:"password" binding:"required,min=6"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	// 重置密码
	password := utils.EncryptPassword(param.Passoword)
	isReset := dao.NewUsersStaffDao().UpdateUserPassword(param.Id, password).Unwrap().(bool)
	if !isReset {
		Response(ctx)("重置密码失败", CodeError, false)(OK)
		return
	}
	Response(ctx)("重置密码成功", CodeSuccess, true)(OK)
}

// 修改用户收款二维码
func HandleUpdateUserQrcode(ctx *gin.Context) {
	param := &struct {
		Id       int    `json:"id" binding:"required,gt=0"`
		ImageUrl string `json:"imageUrl"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUserQrcode(param.Id, param.ImageUrl).Unwrap())(OK)
}

// HandleUpdateUserDeleteStatus 更新代理商用户删除状态
func HandleUpdateUserDeleteStatus(ctx *gin.Context) {
	param := &struct {
		Id int `json:"id" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	Response(ctx)(
		"删除成功",
		CodeSuccess,
		dao.NewUserDao().UpdateUserDeleteStatus(param.Id, 2).Unwrap(),
	)(OK)
}

// HandleDeleteUser 删除代理商用户信息
func HandleDeleteUser(ctx *gin.Context) {
	param := &struct {
		Id int `json:"id" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	// 判断 用户名下是否有子用户
	c := dao.NewUserDao().CountUserByParentId(param.Id).Unwrap().(int64)
	if c > 0 {
		Response(ctx)("删除失败,存在下级用户", CodeSuccess, "删除失败,存在下级用户")(OK)
		return
	}

	// 判断 用户名下是否有直属门店
	cp := dao.NewUserDao().CountPlaceByUserId(param.Id).Unwrap().(int64)
	if cp > 0 {
		Response(ctx)("删除失败,存在下级门店", CodeSuccess, "删除失败,存在下级门店")(OK)
		return
	}

	isDelete := dao.NewUserDao().DeleteUser(param.Id).Unwrap().(bool)
	//删除统计数据
	if isDelete {
		Response(ctx)("删除成功", CodeSuccess, dao.NewUserDao().DeleteStatistical(param.Id))(OK)
	}

}

func HandleDeletePlaceUser(ctx *gin.Context) {
	param := &struct {
		Id int `json:"id" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	// 判断商户是否绑定了设备
	total := dao.NewDeviceDao().GetDeviceCountByPlaceId(param.Id).Unwrap().(int64)
	log.Println("000是否能:", total)
	if total > 0 {
		log.Println("1111删除id:", param.Id)
		Response(ctx)("删除失败，请先解绑设备", CodeSuccess, false)(OK)
		return
	}

	// 直属删除过来只能删除商户，不能删除用户！！！！！！！
	log.Println("222删除id:", param.Id)

	placeInfo := dao.NewPlaceDao().GetPlaceDetailById(param.Id).Unwrap().(*placemodel.PlaceModel)

	Response(ctx)("删除成功", CodeSuccess, dao.NewUserDao().DeleteAllPlaceUser(param.Id, placeInfo.UserID).Unwrap())(OK)

	//Response(ctx)("删除成功", CodeSuccess, dao.NewUserDao().DeletePlaceUser(param.Id).Unwrap())(OK) // 软删除

}

// 通过userId获取分成信息
func HandleGetProfits(ctx *gin.Context) {
	param := &struct {
		UserId int `json:"user_id"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewUserDao().GetProfitsByUserId(param.UserId).Unwrap())(OK)
}

// 获取上级代理商列表
func HandleGetParentUser(ctx *gin.Context) {
	Response(ctx)("", CodeSuccess, dao.NewUserDao().GetSupAgentUserList().Unwrap())(OK)
}

//上传二维码
func HandleQRCodePathUpload(c *gin.Context) {
	//param := &struct {
	//	Id int `json:"id" form:"id"`
	//}{}
	//dingo.ErrorIf(c.Bind(param)).Unwrap()

	file, err := c.FormFile("file")

	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
		return
	}
	//获取用户Id
	userId, _ := strconv.Atoi(c.PostForm("id"))

	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))
	// 判断 文件类型
	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		Response(c)("上传失败!文件类型错误", CodeError, nil)(Error)
	}
	// 判断 文件后缀
	if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
		Response(c)("上传失败!只允许png,jpg,gif,jpeg文件", CodeError, nil)(Error)
	}

	// 判断 文件大小 1024*1024*10
	if file.Size > 10485760 {
		Response(c)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
		return
	}
	fileName := utils.Str2Md5(fmt.Sprintf("%s%s", file.Filename, time.Now().String()))

	//拼接后缀
	fileName += fileExt

	log.Println("开始上传二维码，当前用户", userId, fileName)

	fileDir := fmt.Sprintf("%s/", global.Cfg.Upload.UploadPath)
	filePath := fmt.Sprintf("%s%s", fileDir, fileName)

	// 判断文件路径是否存在
	ok, err := utils.PathExists(fileDir)
	dingo.ErrorIf(err).Unwrap()
	if !ok {
		dingo.ErrorIf(os.MkdirAll(fileDir, os.ModePerm)).Unwrap()
	}

	// 保存文件
	dingo.ErrorIf(c.SaveUploadedFile(file, filePath)).Unwrap()
	//param := &paysetting.PaySetting{}
	//入库
	//updateVal := map[string]interface{}{
	//	"wx_income_qrcode": global.Cfg.Upload.QrcodeUploadReqPath + fileName,
	//}
	log.Println("上传二维码图片，", global.Cfg.Upload.QrcodeUploadReqPath+fileName, "当前用户", userId)
	userModel := &users.UserModel{}
	userModel.WxIncomeQrcode = global.Cfg.Upload.QrcodeUploadReqPath + fileName
	dao.NewUserDao().UpdateUserQRCode(userId, userModel).Unwrap()

	//响应给前端
	Response(c)("", CodeSuccess, utils.Join(global.Cfg.Upload.QrcodeUploadReqPath, fileName))(OK)

}

//阿里OSS上传文件
func HandleAliOssUploadImage(c *gin.Context) {
	file, err := c.FormFile("file")

	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
	}
	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))
	// 判断 文件类型
	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		Response(c)("上传失败!文件类型错误", CodeError, nil)(Error)
	}
	// 判断 文件后缀
	if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
		Response(c)("上传失败!只允许png,jpg,gif,jpeg文件", CodeError, nil)(Error)
	}
	// 判断 文件大小 1024*1024*10
	if file.Size > 10485760 {
		Response(c)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
	}
	fileName := utils.Str2Md5(fmt.Sprintf("%s%s", file.Filename, time.Now().String()))
	//访问域名
	endpoint := global.Cfg.Ali.AliossEndpoint
	accessKeyId := global.Cfg.Ali.AccessKey
	accessKeySecret := global.Cfg.Ali.AccessKeySecret
	bucketName := global.Cfg.Ali.AliossBucketName
	//上传文件到OSS时需要指定包含文件后缀在内的完整路径。
	dir := global.Cfg.Ali.AliossUploadImgDir + fileName + fileExt
	// 创建OSSClient实例。
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		log.Println("AliOssUploadImage 文件上传失败", err)
		Response(c)("文件上传失败!", CodeError, nil)(Error)
		return
	}
	// 获取存储空间。
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Println("AliOssUploadImage 文件上传失败", err)
		Response(c)("文件上传失败!", CodeError, nil)(Error)
		return
	}

	fileIo, err := file.Open()
	// 上传文件流。
	err = bucket.PutObject(dir, fileIo)
	if err != nil {
		log.Println("AliOssUploadImage 文件上传失败", err)
		Response(c)("文件上传失败!", CodeError, nil)(Error)
		return
	}
	//拼接域名返回给前端
	filePath := global.Cfg.Ali.AliossPath + "/" + dir
	Response(c)("", CodeSuccess, filePath)(OK)
	return
}

//合作登记列表
func HandleCooperationRegisterList(c *gin.Context) {
	// 请求参数处理
	param := &request.CooperationRegisterReq{}
	dingo.ErrorIf(c.Bind(&param)).Unwrap()

	// 获取当前用户的的下级用户列表
	data := dao.NewUserDao().GetCooperationRegisterList(param)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

//合作登记新增
func HandleCreateCooperationRegister(c *gin.Context) {
	param := &users.CooperationRegister{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.CreateAt = time.Now().Format("2006-01-02 15:04:05")
	Response(c)("", CodeInsertSuccess, dao.NewUserDao().CreateCooperationRegister(param).Unwrap())(OK)
}

//合作登记修改
func HandleUpdateCooperationRegister(c *gin.Context) {
	param := &users.CooperationRegister{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess, dao.NewUserDao().UpdateCooperationRegister(param).Unwrap())(OK)
}

//合作登记删除
func HandleDeleteCooperationRegister(c *gin.Context) {
	param := &users.CooperationRegister{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeDeleteSuccess, dao.NewUserDao().DeleteCooperationRegister(param.ID).Unwrap())(OK)
}
